//
// Created by syj on 2024/3/14.
//

#ifndef TRANSMIDDLE_LOG_MSG_H
#define TRANSMIDDLE_LOG_MSG_H

#include <chrono>
#include <stdexcept>
#include <string>

#include "middle/log/common/common.h"

namespace log
{
    /**
 * 日志消息
 */
    struct LogMsg {
        std::string id;
        std::string context;
        log::LogLevel level;
        uint64_t time;
        size_t thread_id;
        size_t color_range_start;
        size_t color_range_end;
        std::string filename;
        int line;
        std::string funcname;
        std::string payload;

        /**
         * @brief 转换构造函数
         * @param id 日志 ID
         * @param spglog::detalils::log_msg 日志消息
         */
        LogMsg(std::string const& id, spdlog::details::log_msg const& msg)
                : id(id),
                  context(msg.logger_name.data(), msg.logger_name.size()),
                  level(msg.level),
                  time(std::chrono::duration_cast<std::chrono::microseconds>(
                          msg.time.time_since_epoch())
                               .count()),
                  thread_id(msg.thread_id),
                  color_range_start(msg.color_range_start),
                  color_range_end(msg.color_range_end),
                  line(msg.source.line),
                  payload(msg.payload.data(), msg.payload.size()) {
            if (msg.source.filename) {
                filename = msg.source.filename;
            }
            if (msg.source.funcname) {
                funcname = msg.source.funcname;
            }
        }

        LogMsg() = default;

        /**
         * @brief 转换为 spdlog::details::log_msg
         * @return spdlog::details::log_msg
         */
        spdlog::details::log_msg ToSpdlogLogMsg() const {
            return spdlog::details::log_msg(
                    std::chrono::system_clock::time_point(std::chrono::microseconds(time)),
                    {filename.c_str(), line, funcname.c_str()}, id, level, payload);
        }

    };
}

#endif //TRANSMIDDLE_LOG_MSG_H
